package com.infonam.jsf.eshop.model;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

public class ForceLoginPhaseListener implements PhaseListener{
	private static final long serialVersionUID = 1L;

	@Override
	public void afterPhase(PhaseEvent arg0) {
		
	}
	@Override
	public void beforePhase(PhaseEvent event) {
		FacesContext context = FacesContext.getCurrentInstance();
		String viewId = context.getViewRoot().getViewId();
		if(viewId.equals("/confirm.xhtml")) {
			Application app = context.getApplication();
			UserHolder uh = app.evaluateExpressionGet(context, "#{userHolder}", UserHolder.class);
			if(uh.getCurrentUser() == null) {
				ViewHandler viewHandler = app.getViewHandler();
				// store current view.
				uh.setOriginalViewId(viewId);
				UIViewRoot viewRoot = viewHandler.createView(context, "/login.xhtml");
				context.setViewRoot(viewRoot);
			}
			
		}
		
	}

	@Override
	public PhaseId getPhaseId() {
		/*
		 * It will be call before and after a certain phase. Which phase? It tells. JSF it
		 * is only interested in the Render Response phase.
		 */
		return PhaseId.RENDER_RESPONSE;
	}

}
